<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="listQuery.username" placeholder="管理员账号" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.role" placeholder="角色" clearable style="width: 130px" class="filter-item">
                <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleCreate">
                新增账号
            </el-button>
        </div>

        <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column label="ID" prop="id" align="center" width="80" />
            <el-table-column label="账号" prop="username" align="center" />
            <el-table-column label="姓名" prop="name" align="center" />
            <el-table-column label="角色" align="center" width="120">
                <template slot-scope="scope">
                    <el-tag>{{ getRoleName(scope.row.role) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
                        {{ scope.row.status === 1 ? '正常' : '禁用' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
            <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">
                        编辑
                    </el-button>
                    <el-button :type="scope.row.status === 1 ? 'danger' : 'success'" size="mini"
                        @click="handleStatusChange(scope.row)">
                        {{ scope.row.status === 1 ? '禁用' : '启用' }}
                    </el-button>
                    <el-button type="danger" size="mini" @click="handleDelete(scope.row)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />

        <!-- 新增/编辑账号对话框 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="100px">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="temp.username" :disabled="!!temp.id" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="!temp.id">
                    <el-input v-model="temp.password" type="password" />
                </el-form-item>
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="temp.name" />
                </el-form-item>
                <el-form-item label="角色" prop="role">
                    <el-select v-model="temp.role" placeholder="请选择角色">
                        <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-radio-group v-model="temp.status">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">禁用</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getAdminList, createAdmin, updateAdmin, deleteAdmin, updateAdminStatus } from '@/api/system'
import Pagination from '@/components/Pagination'

export default {
    name: 'Admin',
    components: { Pagination },
    data() {
        return {
            list: [],
            total: 0,
            listLoading: false,
            listQuery: {
                page: 1,
                limit: 10,
                username: undefined,
                role: undefined
            },
            roleOptions: [
                { label: '超级管理员', value: 'admin' },
                { label: '普通管理员', value: 'editor' }
            ],
            dialogVisible: false,
            dialogTitle: '',
            temp: {
                id: undefined,
                username: '',
                password: '',
                name: '',
                role: '',
                status: 1
            },
            rules: {
                username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
                role: [{ required: true, message: '请选择角色', trigger: 'change' }],
                status: [{ required: true, message: '请选择状态', trigger: 'change' }]
            }
        }
    },
    created() {
        this.getList()
    },
    methods: {
        async getList() {
            this.listLoading = true
            try {
                const { data } = await getAdminList(this.listQuery)
                this.list = data.items
                this.total = data.total
            } catch (error) {
                console.error('获取管理员列表失败:', error)
            }
            this.listLoading = false
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleCreate() {
            this.dialogTitle = '新增管理员'
            this.dialogVisible = true
            this.temp = {
                id: undefined,
                username: '',
                password: '',
                name: '',
                role: '',
                status: 1
            }
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        handleUpdate(row) {
            this.dialogTitle = '编辑管理员'
            this.dialogVisible = true
            this.temp = Object.assign({}, row)
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
            })
        },
        getRoleName(role) {
            const roleMap = {
                admin: '超级管理员',
                editor: '普通管理员'
            }
            return roleMap[role] || role
        },
        async handleStatusChange(row) {
            try {
                const newStatus = row.status === 1 ? 0 : 1
                const statusText = newStatus === 1 ? '启用' : '禁用'
                await this.$confirm(`确认${statusText}该管理员账号吗？`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                await updateAdminStatus({
                    id: row.id,
                    status: newStatus
                })
                this.$message.success(`${statusText}成功`)
                this.getList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('更新管理员状态失败:', error)
                    this.$message.error('操作失败')
                }
            }
        },
        async handleDelete(row) {
            try {
                await this.$confirm('确认删除该管理员账号吗？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                await deleteAdmin(row.id)
                this.$message.success('删除成功')
                this.getList()
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('删除管理员失败:', error)
                    this.$message.error('删除失败')
                }
            }
        },
        async submitForm() {
            this.$refs['dataForm'].validate(async (valid) => {
                if (valid) {
                    try {
                        if (this.temp.id) {
                            await updateAdmin(this.temp)
                        } else {
                            await createAdmin(this.temp)
                        }
                        this.$message.success(this.temp.id ? '修改成功' : '新增成功')
                        this.dialogVisible = false
                        this.getList()
                    } catch (error) {
                        console.error(this.temp.id ? '修改管理员失败:' : '新增管理员失败:', error)
                        this.$message.error(this.temp.id ? '修改失败' : '新增失败')
                    }
                }
            })
        }
    }
}
</script>

<style scoped>
.filter-container {
    padding-bottom: 10px;
}
</style> 